﻿using Antlr4.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace libC
{
    /// <summary>
    /// 语法树节点
    /// </summary>
    public class stNode
    {
        public string type;
        public string text;
        public bool terminal;
        public List<stNode> children;
        public int srca;
        public int srcb;
        public static stNode From(Antlr4.Runtime.Tree.IParseTree antlrnode, IVocabulary tokentypes, string[] rulenames)
        {
            stNode stNode = new stNode();
            stNode.text = antlrnode.GetText();
            stNode.srca = antlrnode.SourceInterval.a;
            stNode.srcb = antlrnode.SourceInterval.b;
            var tstNode = antlrnode as Antlr4.Runtime.Tree.ITerminalNode;
            if (tstNode != null)
            {
                stNode.type = tokentypes.GetDisplayName(tstNode.Symbol.Type);
                stNode.terminal = true;
            }
            else
            {
                var rstNode = antlrnode as Antlr4.Runtime.RuleContext;
                stNode.type = rulenames[rstNode.RuleIndex];
            }
            if (antlrnode.ChildCount > 0)
            {
                stNode.children = new List<stNode>();
                for (var i = 0; i < antlrnode.ChildCount; i++)
                {
                    stNode.children.Add(stNode.From(antlrnode.GetChild(i), tokentypes, rulenames));
                }
            }
            return stNode;
        }
    }
}
